﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace CarPublishing
{
    public partial class CarPublishing : System.Web.UI.Page
    {
        private static List<Producer> producers;
        private static List<string> extras;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                producers = new List<Producer>();
                producers.Add(new Producer("BMW", new string[] { "A3", "A4", "A5" }));
                producers.Add(new Producer("Volkswagen", new string[] { "Beetle", "Golf", "Polo" }));
                producers.Add(new Producer("Ford", new string[] { "Focus", "Ka", "Fiesta", "Mondeo" }));

                this.producer.DataSource = producers;
                this.producer.DataBind();

                extras = new List<string>();
                extras.AddRange(new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" });
                this.carExtras.DataSource = extras;
                this.carExtras.DataBind();

                this.engineType.DataSource = new string[] {"1.6 petrol","1.6 diesel","6.4 W12 petrol" };
                this.engineType.DataBind();
            }

        }

        protected void ProducerChanged(object sender, EventArgs e)
        {
            string producerId = this.producer.SelectedValue;
            Producer p = producers.First(x => x.Name == producerId);

            this.model.DataSource = p.Models;
            this.model.DataBind();

            UpdateSelectedInfo(sender, e);
        }

        protected void UpdateSelectedInfo(object sender, EventArgs e)
        {
            string htmlLine = "<br/>";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Format("Car producer:{0}", this.producer.SelectedValue));
            sb.Append(htmlLine);
            if (this.model.SelectedValue != null)
            {
                sb.AppendLine(string.Format("Model:{0}", this.model.SelectedValue));
            }
            sb.Append(htmlLine);
            sb.AppendLine("Extras:"); 
            sb.Append(htmlLine);

            ListItemCollection coll = this.carExtras.Items;
            foreach (ListItem item in coll)
            {
                if (item.Selected)
                {
                    sb.AppendLine(item.Text);
                    sb.Append(htmlLine);
                }
            }

            sb.AppendLine(string.Format("Endgine: {0}", this.engineType.SelectedValue));
            sb.Append(htmlLine);
            this.selected.Text = sb.ToString();
        }

    }
}